﻿import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'menstrual_cycle_calendar_logic.dart';

/// 生理周期日历页面
class MenstrualCycleCalendarView
    extends GetView<MenstrualCycleCalendarLogic> {
  const MenstrualCycleCalendarView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Obx(() {
          if (controller.state.isLoading.value) {
            return const Center(
              child: CircularProgressIndicator(
                color: Color(0xFFFF6B35),
              ),
            );
          }
          
          return Column(
            children: [
              // 头部
              _buildHeader(),

              // 月份导航
              _buildMonthNavigation(),

              // 日历
              Expanded(
                child: Container(
                  margin: EdgeInsets.symmetric(horizontal: 20.w),
                  decoration: BoxDecoration(
                    color: Colors.grey[900],
                    borderRadius: BorderRadius.circular(20.r),
                  ),
                  child: Column(
                    children: [
                      // 生理期预计6天结束提示
                      _buildPeriodNotification(),

                      // 日历网格
                      _buildCalendarGrid(),

                      // 图例
                      _buildLegend(),

                      // 底部按钮
                      _buildBottomButtons(),
                    ],
                  ),
                ),
              ),
            ],
          );
        }),
      ),
    );
  }

  /// 构建头部
  Widget _buildHeader() {
    return Padding(
      padding: EdgeInsets.all(20.w),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => Get.back(),
            child: Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: Colors.grey[800],
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: Icon(
                Icons.arrow_back_ios_new,
                color: Colors.white,
                size: 20.sp,
              ),
            ),
          ),
          Expanded(
            child: Center(
              child: Text(
                '生理周期',
                style: TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              // 跳转到今天
              controller.jumpToToday();
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
              decoration: BoxDecoration(
                color: const Color(0xFFFF6B35),
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: Text(
                '今天',
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w600,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建月份导航
  Widget _buildMonthNavigation() {
    return Obx(() {
      return Padding(
        padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            GestureDetector(
              onTap: () => controller.previousMonth(),
              child: Icon(
                Icons.chevron_left,
                color: Colors.white,
                size: 28.sp,
              ),
            ),
            SizedBox(width: 20.w),
            Text(
              '${controller.state.currentDate.value.year} ${controller.state.currentDate.value.month}月',
              style: TextStyle(
                fontSize: 20.sp,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
            SizedBox(width: 20.w),
            GestureDetector(
              onTap: () => controller.nextMonth(),
              child: Icon(
                Icons.chevron_right,
                color: Colors.white,
                size: 28.sp,
              ),
            ),
          ],
        ),
      );
    });
  }

  /// 构建生理期通知
  Widget _buildPeriodNotification() {
    return Obx(() {
      final notification = controller.state.periodNotification.value;
      
      // 如果没有通知内容，不显示
      if (notification.isEmpty) {
        return const SizedBox.shrink();
      }
      
      return Container(
        margin: EdgeInsets.all(20.w),
        padding: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          color: Colors.black,
          borderRadius: BorderRadius.circular(12.r),
        ),
        child: Row(
          children: [
            Icon(
              Icons.volume_up_outlined,
              color: Colors.white,
              size: 20.sp,
            ),
            SizedBox(width: 12.w),
            Expanded(
              child: Text(
                notification,
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.white,
                ),
              ),
            ),
          ],
        ),
      );
    });
  }

  /// 构建日历网格
  Widget _buildCalendarGrid() {
    return Obx(() {
      return Expanded(
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 20.w),
          child: Column(
            children: [
              // 星期头部
              _buildWeekHeader(),

              SizedBox(height: 16.h),

              // 日历网格
              Expanded(
                child: GridView.builder(
                  physics: const NeverScrollableScrollPhysics(),
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 7,
                    childAspectRatio: 1,
                  ),
                  itemCount: controller.getDaysInMonth(),
                  itemBuilder: (context, index) {
                    return _buildDayCell(index);
                  },
                ),
              ),
            ],
          ),
        ),
      );
    });
  }

  /// 构建星期头部
  Widget _buildWeekHeader() {
    final weekDays = ['日', '一', '二', '三', '四', '五', '六'];

    return Row(
      children: weekDays.map((day) {
        return Expanded(
          child: Center(
            child: Text(
              day,
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.grey[400],
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        );
      }).toList(),
    );
  }

  /// 构建日期单元格
  Widget _buildDayCell(int index) {
    return Obx(() {
      final day = controller.getDayForIndex(index);
      final dayStatus = controller.getDayStatus(day);
      final isToday = controller.isToday(day);
      final isCurrentMonth = controller.isCurrentMonth(day);

      Color? backgroundColor;
      Color textColor = Colors.white;

      // 根据状态设置颜色
      switch (dayStatus) {
        case DayStatus.predictedPeriod:
          backgroundColor = Colors.pink.withOpacity(0.3);
          break;
        case DayStatus.period:
          backgroundColor = Colors.pink;
          break;
        case DayStatus.ovulationDay:
          backgroundColor = Colors.blue;
          break;
        case DayStatus.ovulationPeriod:
          backgroundColor = Colors.orange;
          break;
        default:
          if (isToday) {
            backgroundColor = Colors.grey[700];
          }
          break;
      }

      if (!isCurrentMonth) {
        textColor = Colors.grey[600] ?? Colors.grey;
      }

      return Container(
        margin: EdgeInsets.all(2.w),
        decoration: BoxDecoration(
          color: backgroundColor,
          shape: BoxShape.circle,
        ),
        child: Center(
          child: Text(
            day.day.toString(),
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: isToday ? FontWeight.bold : FontWeight.normal,
              color: textColor,
            ),
          ),
        ),
      );
    });
  }

  /// 构建图例
  Widget _buildLegend() {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 30.w),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              _buildLegendItem(Colors.pink.withOpacity(0.3), '预测生理期'),
              SizedBox(width: 20.w),
              _buildLegendItem(Colors.pink, '生理期'),
            ],
          ),
          SizedBox(height: 12.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              _buildLegendItem(Colors.blue, '排卵日'),
              SizedBox(width: 20.w),
              _buildLegendItem(Colors.orange, '排卵期'),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建图例项
  Widget _buildLegendItem(Color color, String label) {
    return Row(
      children: [
        Container(
          width: 12.w,
          height: 12.w,
          decoration: BoxDecoration(
            color: color,
            shape: BoxShape.circle,
          ),
        ),
        SizedBox(width: 8.w),
        Text(
          label,
          style: TextStyle(
            fontSize: 12.sp,
            color: Colors.grey[400],
          ),
        ),
      ],
    );
  }

  /// 构建底部按钮
  Widget _buildBottomButtons() {
    return Padding(
      padding: EdgeInsets.all(20.w),
      child: Column(
        children: [
          // 通知提醒按钮
          GestureDetector(
            onTap: () {
              Get.toNamed('/menstrual-cycle/notification');
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
              decoration: BoxDecoration(
                color: Colors.black,
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: Row(
                children: [
                  Container(
                    width: 32.w,
                    height: 32.w,
                    decoration: BoxDecoration(
                      color: Colors.pink,
                      borderRadius: BorderRadius.circular(8.r),
                    ),
                    child: Icon(
                      Icons.notifications_outlined,
                      color: Colors.white,
                      size: 18.sp,
                    ),
                  ),
                  SizedBox(width: 12.w),
                  Expanded(
                    child: Text(
                      '通知提醒',
                      style: TextStyle(
                        fontSize: 16.sp,
                        color: Colors.white,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                  Icon(
                    Icons.arrow_forward_ios,
                    color: Colors.grey[500],
                    size: 16.sp,
                  ),
                ],
              ),
            ),
          ),

          SizedBox(height: 12.h),

          // 生理周期设置按钮
          GestureDetector(
            onTap: () async {
              await Get.toNamed('/menstrual-cycle/setup');
              // 从设置页返回后刷新数据
              controller.refreshData();
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
              decoration: BoxDecoration(
                color: Colors.black,
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: Row(
                children: [
                  Container(
                    width: 32.w,
                    height: 32.w,
                    decoration: BoxDecoration(
                      color: Colors.pink,
                      borderRadius: BorderRadius.circular(8.r),
                    ),
                    child: Icon(
                      Icons.settings_outlined,
                      color: Colors.white,
                      size: 18.sp,
                    ),
                  ),
                  SizedBox(width: 12.w),
                  Expanded(
                    child: Text(
                      '生理周期设置',
                      style: TextStyle(
                        fontSize: 16.sp,
                        color: Colors.white,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                  Icon(
                    Icons.arrow_forward_ios,
                    color: Colors.grey[500],
                    size: 16.sp,
                  ),
                ],
              ),
            ),
          ),

          SizedBox(height: 12.h),

          // 更新本月生理期按钮
          GestureDetector(
            onTap: () {
              controller.showUpdatePeriodDialog();
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
              decoration: BoxDecoration(
                color: Colors.black,
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: Row(
                children: [
                  Container(
                    width: 32.w,
                    height: 32.w,
                    decoration: BoxDecoration(
                      color: Colors.pink,
                      borderRadius: BorderRadius.circular(8.r),
                    ),
                    child: Icon(
                      Icons.edit_calendar,
                      color: Colors.white,
                      size: 18.sp,
                    ),
                  ),
                  SizedBox(width: 12.w),
                  Expanded(
                    child: Text(
                      '更新本月生理期',
                      style: TextStyle(
                        fontSize: 16.sp,
                        color: Colors.white,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                  Icon(
                    Icons.arrow_forward_ios,
                    color: Colors.grey[500],
                    size: 16.sp,
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
